package com.gvsoft.conns;

import com.gvsoft.Config;
import com.gvsoft.common.CommonTools;

import java.io.IOException;
import java.nio.channels.SocketChannel;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:gvMsgRouting
 * Author: zhaoqiubo
 * Date: 15/8/5
 * Time: 下午4:24
 * Desc: 超时通道、失效通道清理线程。
 */

public class ConnTimeoutCleanThread implements Runnable {
    /**
     * 超时时间
     */
    private int outTime;
    /**
     * 执行周期
     */
    private int cycle;

    private static Logger logger = LogManager.getLogger(ConnTimeoutCleanThread.class.getName());

    public ConnTimeoutCleanThread(int outTime, int cycle) {
        this.outTime = outTime;
        this.cycle = cycle;
    }

    public void run() {

        logger.info("定期通道清理线程启动……");
        while (true) {
            logger.info("定期通道清理开启……");

            Map<String, GVConnection> connCache = GVConnTools.getConnCache();

            for (String token : connCache.keySet()) {
                int currentTime = CommonTools.systemTimeUtc();
                GVConnection gvConn = GVConnTools.getConnByToken(token);
                SocketChannel socketChannel = gvConn.getChannel();
                if (!socketChannel.isOpen()) {
                    try {
                        socketChannel.close();
                        logger.info("清理了关闭的连接：clientId:<" + token + ">");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else if (currentTime - gvConn.getLastAccessTime() > outTime) {
                    if (socketChannel.isOpen()) {
                        try {
                            socketChannel.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    GVConnTools.removeConnByToken(token);
                    logger.info("清理了超时的连接：clientId:<" + token + ">");
                }
                try {
                    Thread.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            logger.info("定期通道清理执行完毕！");
            try {
                Thread.sleep(cycle * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
